const express = require("express")
const http = require('http')
const app = express()
const server = http.createServer(app)
// 连接数据库
require("./utils/voteConnect")

server.listen(9000, () => {
  console.log("http://localhost:9000");
})

// 导入socket
const socketIO = require('socket.io')
const io = socketIO(server)

// 导入数据库新增用户model
const { voted, addVote, voteFind, addChoose } = require("./model/vote")

// 处理post传参
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 静态资源托管
app.use("/client", express.static("client"))

app.all("/", (req, res) => {
  res.redirect("/client")
})

io.on("connection", scoket => {
  // 与客户端建立连接
  console.log("连接已成立");

  scoket.on("vote", (id) => {
    io.emit("vote", id)
  })
})

// 投票路由
// post需要传递的参数navigator.appVersion
/* 
  浏览器平台和版本信息: navigator.appVersion
  客户机发送服务器的user-agent头部的值: navigator.userAgent
  投票选择的id
  用户名
*/
app.post("/vote", async (req, res) => {
  const { appVersion, userAgent, id, username } = req.body
  if (!appVersion || !userAgent || !id || !username) {
    return res.send({
      code: "0",
      message: "传参不实"
    })
  }

  const response = await voted(id, username, appVersion, userAgent)
  if (response.state) {
    return res.send({
      code: 1,
      message: "投票成功",
      data: response.data
    })
  } else {
    return res.send({
      code: 0,
      message: response.message
    })
  }
})

// 创建投票路由
app.post("/create", async (req, res) => {
  let { options, password } = req.body
  if (password !== "123321") return res.send({
    code: 0,
    message: "密码错误"
  })
  // 把传递过来的数组转为对象
  // 首先需要去重
  // options = new Set(...options)
  console.log(options)
  // 存放选项数组:key为选项,value为选择人数,初始化都为0
  const obj = {}
  options.forEach(ele => {
    obj[ele] = 0
  })
  const response = await addVote(obj)
  if (response.state == 1) {
    return res.send({
      code: 1,
      message: "创建投票成功"
    })
  }
  res.send({
    code: 0,
    message: "创建投票失败"
  })
})

// 渲染投票
app.get("/getVote", async (req, res) => {
  const response = await voteFind()
  if (response.state == 1) {
    return res.send({
      code: 1,
      message: "获取成功",
      data: response.data
    })
  }
  res.send({
    code: 0,
    message: response.message
  })
})

// 增加投票
app.post("/add", async (req, res) => {
  const {option} = req.body
  const response = await voteFind()

  // 选项对应投票数
  let options = JSON.parse(response.data[0].options)

  // 先判断对应选项是否已经存在选项中
  const exit = Object.keys(options).findIndex((ele) => ele === option)

  if (exit != -1) {
    return res.send({
      code: 0,
      message: "选项已存在"
    })
  }
  
  options[option] = 0
  // 转化为json,准备放在数据库中
  options = JSON.stringify(options)

  const r = await addChoose(options)
  if (r.state == 1) {
    return res.send({
      code: 1,
      message: "增加选项成功"
    })
  }
  res.send({
    code: 0,
    message: r.message
  })
})